package com.lhy.web.controller;

import com.lhy.model.User;
import com.lhy.web.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.annotation.RequestScope;

import java.util.List;

/**
 * Created by xuhaitao on 17/2/25.
 */
@RestController
public class UserController {

    @Autowired
    private UserRepository userRepository;

    /**
     * 查询用户列表信息
     * @return
     */
    @GetMapping("/users")
    public List<User> userList(){
        return userRepository.findAll();
    }

    /**
     * 添加用户
     * @param name
     * @param pwd
     * @param age
     * @return
     */
    @PostMapping("/users")
    public User userAdd(@RequestParam(name = "name") String name,
                        @RequestParam(name = "pwd")String pwd,
                        @RequestParam(name = "age")int age){
        User user = new User();
        user.setName(name);
        user.setPwd(pwd);
        user.setAge(age);
        return userRepository.save(user);
    }

    @GetMapping("/users/{id}")
    public User findUserById(@PathVariable("id")Long id){
        return userRepository.findOne(id);
    }
    @PutMapping("/users/{id}")
    public User userUpdate(@PathVariable("id") Long id,
                           @RequestParam(name = "name") String name,
                           @RequestParam(name = "pwd")String pwd,
                           @RequestParam(name = "age")int age){
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setPwd(pwd);
        user.setAge(age);
        return userRepository.save(user);
    }
    @DeleteMapping("/users/{id}")
    public void userDelete(@PathVariable("id")Long id){
        userRepository.delete(id);
    }

}
